'use strict';
cimsTech.directive('zTree', ['SCADA', 'fileService', 'ErrMsg', '$rootScope', function(SCADA, fileList, ErrMsg, $rootScope) {
    return {
        name: 'zTree',
        template: '<ul class="ztree" id="modelTree"></ul>',
        scope: {
            asyncUrl: '@asyncUrl',
            asyncType: '@asyncType',
            asyncFilter: '@asyncFilter'
        },
        replace: true,
        link: function($scope) {
            $scope.url = '';
            var zTree;
            $scope.$on('destroyTree', function() {
                if(zTree) {
                    zTree.destroy();
                }
            });
            $scope.$on('reAsyncChildNodes', function() {
                if(zTree) {
                    zTree.reAsyncChildNodes(null, 'refresh');
                }
            });
            $scope.$on('initTree', function(event, data) {
                $scope.url = data;
                if(zTree) {
                    zTree.destroy();
                }
                var setting = {
                    async: {
                        enable: true,
                        url: $scope.asyncUrl,
                        type: $scope.asyncType || 'post',
                        autoParam: ['id', 'name=n', 'level=lv'],
                        otherParam: {
                            'url': $scope.url
                        },
                        dataFilter: $scope.asyncFilter ? ajaxDataFilter : undefined
                    },
                    view: {
                        showLine: false,
                        nameIsHTML: true,
                        showIcon: false,
                        //dblClickExpand: false,
                        expandSpeed: 200,
                        showTitle: false
                    },
                    callback: {
                        onDblClick: callback,
                        beforeExpand: zTreeOnExpand
                    }
                };
                zTree = $.fn.zTree.init($('#modelTree'), setting);
            });
            function callback(event, treeId, treeNode) {
                if(!treeNode) {
                    return;
                }
                var param = {
                    url: $scope.url,
                    id: treeNode.id
                };
                console.log($scope.url + '     ' + treeNode.id);
                switch($scope.asyncUrl) {
                case 'rest/Model/get' :
                    SCADA.asyncValueList(param);
                    break;
                case 'rest/getFileDir' :
                    fileList.asyncFileList(param);
                    break;
                default :
                }
            }

            function zTreeOnExpand(treeId, treeNode) {
                if($scope.asyncUrl === 'rest/getFileDir') {
                    $scope.$emit('expandNode', treeNode);
                }
            }

            function ajaxDataFilter(treeId, parentNode, responseData) {
                var data = [];
                if(responseData.iecResponseMessage === 'ERROR') {
                    ErrMsg.show(responseData.iecResponseCause);
                } else if(responseData.nodes instanceof Array) {
                    responseData.nodes.sort(function(a, b) {
                        if(a.isParent === b.isParent) {
                            return a.title > b.title ? 1 : -1;
                        } else {
                            return b.isParent ? 1 : -1;
                        }
                    });
                    $rootScope.$apply(function() {
                        fileList.asyncFileList(angular.copy(responseData.nodes));
                    });
                    angular.forEach(responseData.nodes, function(node) {
                        // fileList.asyncFileList(node);
                        if(!node.isParent) {
                            node.name = '<span class="fa fa-file"></span>' + node.title.replace('\\', '');
                        } else {
                            node.name = '<span class="fa fa-folder"></span>' + node.title.replace('\\', '');
                        }
                        data.push(node);
                    });
                }
                return data;
            }
        }
    };
}]).directive('ngSwitcher', function() {
    return {
        restrict: 'AE',
        template: '<button class="switch" data-ng-class="{\'switch-left\': !connectPool[activeConn].reportStatus, \'switch-right\': connectPool[activeConn].reportStatus}" data-ng-click="switchReport()" data-ng-disabled=\'isDisable\'>' + '<div class="switch-button">&nbsp;</div>' + '</button>'
    };
}).directive('connectPool', ['ConnList', 'ConnectService', 'sWSocket', '$rootScope', '$localStorage', function(ConnList, ConnectService, sWSocket, $rootScope, $localStorage) {
    return {
        name: 'connectPool',
        restrict: 'EA',
        templateUrl: 'pages/connectPool.html',
        replace: true,
        link: function($scope) {
            $scope.connectPool = ConnList.getConnectList();
            $rootScope.activeConn = 0;
            $scope.connectName = $localStorage.connPool;
            sWSocket.addCallback('event', function(data) {
                $scope.$apply(function($scope) {
                    $scope.connectPool.getConnByIp(data.ip).isConnect = data.event;
                });
            }).addCallback('updateStatus', function(data) {
                $scope.$apply(function($scope) {
                    $scope.connectPool.getConnByIp(data.ip).reportStatus = true;
                });
            });
            $scope.connectAll = function() {
                angular.forEach($scope.connectPool, function(connect) {
                    if(connect.isConnect === 'disconnect' && connect.ip) {
                        connect.isConnect = 'connecting';
                        ConnectService.connect(connect);
                    }
                });
                $scope.$broadcast('initTree', $scope.connectPool[$rootScope.activeConn].ip);
            };
            $scope.changeConn = function(index) {
                $rootScope.activeConn = index;
            };
            $scope.newConn = function() {
                ConnList.addConnect();
                $rootScope.activeConn = $scope.connectPool.length - 1; // ConnList.changeConn($scope.activeConn);
            };
            $scope.removeConn = function(index, conn) {
                if(conn.ip) {
                    ConnectService.removeConn(conn);
                }
                ConnList.removeConn(conn);
                $rootScope.activeConn = $scope.connectPool[index] ? index : index - 1;
            };
        }
    };
}]).directive('connectForm', ['ConnList', 'ConnectService', '$rootScope', function(ConnList, ConnectService, $rootScope) {
    return {
        name: 'connectForm',
        restrict: 'EA',
        template: '<div class="col-sm-10 navbar-form navbar-right" role="connect"> <div class="form-group"> <input class="form-control" id="ip_input" type="text" maxlength="15" data-ng-disabled="connectPool[activeConn].isConnect !=\'disconnect\'" data-ng-model="connectPool[activeConn].ip" required> <button class="btn btn-default" data-ng-disabled="isDisable" data-ng-class="{\'connect\': connectPool[activeConn].isConnect===\'connected\', \'disconnect\':connectPool[activeConn].isConnect !=\'connected\'}" data-ng-click="connectDevice(connectPool[activeConn].isConnect)"></button> </div> </div>',
        replace: true,
        link: function($scope) {
            $scope.connectPool = ConnList.getConnectList();
            $scope.isDisable = false;
            $scope.connectDevice = function(args) {
                $scope.isDisable = true;
                switch(args) {
                case 'disconnect' :
                    $scope.connectPool[$rootScope.activeConn].isConnect = 'connecting';
                    ConnectService.connect($scope.connectPool[$rootScope.activeConn]).then(function() {
                        $scope.$broadcast('initTree', $scope.connectPool[$rootScope.activeConn].ip);
                        $scope.isDisable = false;
                    }, function() {
                        $scope.isDisable = false;
                    });
                    break;
                case 'connected' :
                    $scope.connectPool[$scope.activeConn].isConnect = 'connecting';
                    ConnectService.tearingConn({
                        url: $scope.connectPool[$rootScope.activeConn].ip
                    }).then(function() {
                        $scope.isDisable = false;
                        $scope.connectPool[$rootScope.activeConn].reportStatus = false;
                        $scope.$broadcast('destroyTree');
                    }, function(ip) {
                        $scope.isDisable = false;
                        $scope.connectPool.getConnByIp(ip).isConnect = 'connected';
                    });
                    break;
                default :
                    break;
                }
            };
        }
    };
}]);